package com.kate.mall.coupon.service.impl;

import com.kate.mall.common.exception.NDException;
import com.kate.mall.coupon.constants.CouponConstant;
import com.kate.mall.coupon.entity.CouponUserEntity;
import com.kate.mall.coupon.service.CouponUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Optional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kate.mall.common.utils.PageUtils;
import com.kate.mall.common.utils.Query;

import com.kate.mall.coupon.dao.CouponDao;
import com.kate.mall.coupon.entity.CouponEntity;
import com.kate.mall.coupon.service.CouponService;

import javax.annotation.Resource;


@Service("couponService")
@Slf4j
public class CouponServiceImpl extends ServiceImpl<CouponDao, CouponEntity> implements CouponService {
    @Resource
    private CouponUserService couponUserService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CouponEntity> page = this.page(
                new Query<CouponEntity>().getPage(params),
                generatorQueryWrapper(params)
        );

        return new PageUtils(page);
    }
    private QueryWrapper generatorQueryWrapper(Map<String, Object> params) {
        QueryWrapper<CouponEntity> queryWrapper = new QueryWrapper<>();
//        if (params.get("couponCode") == null){
//            queryWrapper.eq("status",params.get("status"));
//            queryWrapper.eq("type",params.get("type"));
//            queryWrapper.eq("tag",params.get("tag"));
//        }else{
//            queryWrapper.eq("code",params.get("couponCode"));
//        }
        //1.查询在platform为全部和移动端
        queryWrapper.eq("platform",0).or().eq("platform",1);
        //2.查询优惠券状态为正常
        queryWrapper.eq("status",0);
        //3.没有被逻辑删除的----mp的逻辑删除的注解，自动查询未删除的数据
        return queryWrapper;
    }

    /**
     * 检测优惠券是否适合
     *
     * @param userId
     * @param couponId
     * @param checkedGoodsPrice
     * @return
     */
    public Optional<CouponEntity> checkCoupon(Integer userId, Integer couponId, Integer userCouponId, BigDecimal checkedGoodsPrice) {
        CouponEntity coupon = getById(couponId);
        if (coupon == null) {
            return Optional.empty();
        }

        CouponUserEntity couponUser = couponUserService.getById(userCouponId);
        if (couponUser == null) {
            couponUser = couponUserService.getOne(new QueryWrapper<CouponUserEntity>().lambda().eq(CouponUserEntity::getUserId,userId)
                    .eq(CouponUserEntity::getCouponId,couponId));
        } else if (!couponId.equals(couponUser.getCouponId())) {
            return Optional.empty();
        }

        if (couponUser == null) {
            return Optional.empty();
        }

        // 检查是否超期
        Short timeType = coupon.getTimeType();
        Short days = coupon.getDays();
        LocalDateTime now = LocalDateTime.now();
        if (timeType.equals(CouponConstant.TIME_TYPE_TIME)) {
            if (now.isBefore(coupon.getStartTime()) || now.isAfter(coupon.getEndTime())) {
                return Optional.empty();
            }
        }
        else if(timeType.equals(CouponConstant.TIME_TYPE_DAYS)) {
            LocalDateTime expired = coupon.getAddTime().plusDays(days);
            if (now.isAfter(expired)) {
                return Optional.empty();
            }
        }
        else {
            return Optional.empty();
        }

        // 检测商品是否符合
        // TODO 目前仅支持全平台商品，所以不需要检测
        Short goodType = coupon.getGoodsType();
        if (!goodType.equals(CouponConstant.GOODS_TYPE_ALL)) {
            throw new NDException("优惠券id:【"+coupon.getId()+"】,领取用户id:【{"+couponUser.getUserId()+"}】,金额：【{"+coupon.getDiscount()+"}】....该商品不支持此优惠券");
        }

        // 检测订单状态
        Short status = couponUser.getStatus();
        if (!status.equals(CouponConstant.STATUS_NORMAL)) {
            throw new NDException("优惠券id:【"+coupon.getId()+"】,领取用户id:【{"+couponUser.getUserId()+"}】,金额：【{"+coupon.getDiscount()+"}】....该优惠券已使用");
        }
        // 如果优惠券为满减劵，检测是否满足最低消费
        if (coupon.getType()==2&&checkedGoodsPrice.compareTo(coupon.getMin()) == -1) {
            throw new NDException("优惠券id:【"+coupon.getId()+"】,领取用户id:【{"+couponUser.getUserId()+"}】,金额：【{"+coupon.getDiscount()+"}】....未达到最低消费");
        }
        log.info("======检验 优惠券完成 :{} ====="+coupon);

        return Optional.ofNullable(coupon);
    }

}